package com.inkrl.user.service.v1;
import java.util.concurrent.*;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inkrl.user.domain.User;
import com.inkrl.user.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service("TokenService")
public class TokenServiceImp implements TokenService {

    @Autowired(required = false)
    private StringRedisTemplate template;
    private ObjectMapper mapper=new ObjectMapper();
    @Override
    public String getTokenByphone(String phone) {
        ValueOperations<String, String> opsForString =template.opsForValue();
        return opsForString.get(phone);
    }

    @Override
    public String newToken(User user) throws JsonProcessingException {
        ValueOperations<String, String> opsForString =template.opsForValue();
        //先调用getTokenByphone方法去查找redis当中是否有存储该手机号对应的redis
        String token = getTokenByphone(user.getPhone());
        if(token!=null){
            //如果有就删除
            template.delete(user.getPhone());
            template.delete(token);
        }
        //新建token，并放入redis中
        token = createToken(user);
        user.setPassword(null);
        opsForString.set(user.getPhone(),token,15,TimeUnit.DAYS);
        opsForString.set(token,mapper.writeValueAsString(user),15,TimeUnit.DAYS);
        return token;
    }

    @Override
    public String getUserJsonByToken(String token) {
        ValueOperations<String, String> opsForString =template.opsForValue();
        //使用token 去获json值 直接返回
        return opsForString.get(token);
    }

    private String createToken(User user) {
        String token="";
        token= JWT.create().withAudience(user.getPhone())
                .sign(Algorithm.HMAC256(System.currentTimeMillis()+user.getPassword()+System.currentTimeMillis()));
        return token;
    }
}
